# import zipfile
#
# from flask import Flask, send_from_directory
# import os
#
# app = Flask(__name__)
#
# # 加载配置文件
# import config
# FILE_DIRECTORY = config.FILE_DIRECTORY
#
# def rename_and_extract(msz_file_path, output_folder):
#     """
#     将文件从.msz重命名为.zip并解压到指定文件夹。
#
#     :param msz_file_path: .msz文件的路径
#     :param output_folder: 解压目标文件夹
#     """
#     # 确保输出文件夹存在
#     if not os.path.exists(output_folder):
#         os.makedirs(output_folder)
#
#     # 重命名文件为.zip
#     zip_file_path = msz_file_path.rsplit('.', 1)[0] + '.zip'
#     os.rename(msz_file_path, zip_file_path)
#
#     # 解压ZIP文件
#     with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
#         zip_ref.extractall(output_folder)
#
#     print(f"File renamed and extracted to {output_folder}")
#
# @app.route('/<path:subpath>/<filename>')
# def download_file(subpath, filename):
#     try:
#         # 构建完整的文件路径
#         full_path = os.path.join(FILE_DIRECTORY, subpath, filename)
#         print(full_path)
#         return send_from_directory(os.path.dirname(full_path), os.path.basename(full_path), as_attachment=True)
#     except FileNotFoundError:
#         return "File not found", 404
#
# if __name__ == '__main__':
#     app.run(host='0.0.0.0', port=5000)
import hashlib
import json
import random
import time

from flask import Flask, request, jsonify, render_template
import os
import zipfile

from pydub import AudioSegment

import table
import config

app = Flask(__name__)

# 设置文件存储的目录
FILE_DIRECTORY = config.FILE_DIRECTORY

@app.route('/upload', methods=['POST'])
def upload_files():
    files = request.files.getlist('files')
    for file in files:
        if file.filename.endswith('.mcz'):
            # 保存文件
            filepath = os.path.join(FILE_DIRECTORY, file.filename)
            file.save(filepath)
            # 调用重命名和解压函数
            output_folder = os.path.splitext(file.filename)[0]  # 根据文件名创建输出文件夹
            rename_and_extract(filepath, output_folder)
    return jsonify({'success': True})

@app.route('/')
def index():
    # realname = get_real_name("D:/PycharmProjects/filesv/少女幻葬")
    # print(extract_artist("D:/PycharmProjects/filesv/少女幻葬/少女幻葬6转45_4k_hd.mc"))
    print(calculate_file_md5("C:/Users/swc010/Documents/filesv/filesv/少女幻葬6转45_4k_hd.mc"))
    return render_template("upload.html")

def get_mp3_duration(mp3_file_path):
    audio = AudioSegment.from_mp3(mp3_file_path)
    duration_seconds = int(len(audio) / 1000)  # pydub的时长是以毫秒为单位
    return duration_seconds

def extract_bpm(mc_file_path):
    # 读取 .mc 文件
    global bpm_info
    with open(mc_file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)  # 解析 JSON 数据
    for entry in data.get('time', []):
        if 'bpm' in entry:
            bpm_info = int(entry['bpm'])
    return bpm_info


def extract_artist(mc_file_path):
    with open(mc_file_path, 'r', encoding='utf-8') as file:
        mc_data = json.load(file)  # 解析 JSON 数据
    try:
        artist = mc_data.get("meta", {}).get("song", {}).get("artist", "Unknown Artist")
        return artist
    except json.JSONDecodeError:
        return "Invalid JSON format"
    
def generate_unique_random_number():
    # 获取当前时间戳（秒）
    current_timestamp = int(time.time())
    
    # 将时间戳转换为字符串，并确保其长度至少为8位
    timestamp_str = str(current_timestamp).zfill(8)
    
    # 返回8位长的数字部分
    return int(timestamp_str[:8])

def get_mc_file_path(directory):
    files = os.listdir(directory)
    mc_files = [file for file in files if file.lower().endswith('.mc')]
    if mc_files:
        benchmark_file = random.choice(mc_files)
        return os.path.join(directory, benchmark_file)
    else:
        return None


def get_real_name(directory):
    files = os.listdir(directory)

    mp3_files = [file for file in files if file.lower().endswith('.mp3')]

    # 如果只有一个 MP3 文件，返回它的名字不包含扩展名的部分
    if len(mp3_files) == 1:
        # 从右侧开始分割文件名，分割一次，取第一部分（不包含扩展名）
        return mp3_files[0].rsplit('.', 1)[0]
    else:
        return None

def get_mc_files(directory):
    # 列出目录下的所有文件
    files = os.listdir(directory)
    
    # 筛选出扩展名为 .mc 的文件
    mc_files = [file for file in files if file.lower().endswith('.mc')]
    
    # 构建完整的文件路径
    mc_files_full_paths = [os.path.join(directory, file) for file in mc_files]
    
    return mc_files_full_paths

def calculate_file_md5(file_path):
    if not os.path.isfile(file_path):
        raise FileNotFoundError(f"The file {file_path} does not exist.")

    md5_hash = hashlib.md5()
    with open(file_path, "rb") as f:  # 打开文件用于读取二进制模式
        for chunk in iter(lambda: f.read(4096), b""):  # 使用 4KB 的块读取文件
            md5_hash.update(chunk)  # 更新 MD5 哈希值
    return md5_hash.hexdigest()  # 返回十六进制的 MD5 值

def rename_and_extract(mcz_file_path, output_folder):
    # 确保输出文件夹存在
    output_path = os.path.join(FILE_DIRECTORY, output_folder)
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    # 重命名文件为.zip
    zip_file_path = os.path.join(FILE_DIRECTORY, f"{output_folder}.zip")
    os.rename(mcz_file_path, zip_file_path)

    # 解压ZIP文件
    with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
        zip_ref.extractall(output_path)

    print(f"File renamed and extracted to {output_path}")

    song_name = output_folder
    sid = generate_unique_random_number()
    real_name = get_real_name(output_path)
    print(os.path.join(output_path,f"{real_name}.mp3"))
    song_length = 0
    bpm = extract_bpm(get_mc_file_path(output_path))
    song_artist = extract_artist(get_mc_file_path(output_path))
    time = song_length
    s_mode = 7
    s_md5 = calculate_file_md5(os.path.join(output_path,f"{real_name}.mp3"))
    s_file_path = config.NET_PATH + "/" + output_folder + "/" + f"{real_name}.mp3"
    img_md5 = calculate_file_md5(os.path.join(output_path,f"{real_name}.png"))
    img_file_path = config.NET_PATH + "/" + output_folder + "/" + f"{real_name}.png"

    print("song_name:"+song_name+"sid:"+str(sid)+"real_name:"+real_name+"bpm:"+str(bpm)+"song_artist:"+song_artist+"s_md5:"+str(s_md5))


    # table.insert_song()
    os.remove(zip_file_path)
    print(f"successfully delete cache: {zip_file_path}")



if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
